package generic;

import java.util.HashSet;
import java.util.Set;

/**
 * 集合运算，并集，交集，差集，对差集
 * a = [1, 2, 3, 4, 5, 6]
 * b = [5, 6, 7, 8, 9, 10]
 */
public class Sets {

    /**
     * 并集 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
     *
     * @param a
     * @param b
     * @param <T>
     * @return
     */
    public static <T> Set<T> union(Set<T> a, Set<T> b) {
        Set<T> res = new HashSet<>(a);
        res.addAll(b);

        return res;
    }

    /**
     * 交集 [5, 6]
     *
     * @param a
     * @param b
     * @param <T>
     * @return
     */
    public static <T> Set<T> intersection(Set<T> a, Set<T> b) {
        Set<T> res = new HashSet<>(a);
        res.retainAll(b);

        return res;
    }

    /**
     * 差集 [1, 2, 3, 4]
     *
     * @param superset
     * @param subset
     * @param <T>
     * @return
     */
    public static <T> Set<T> difference(Set<T> superset, Set<T> subset) {
        Set<T> res = new HashSet<>(superset);
        res.removeAll(subset);

        return res;
    }

    /**
     * 对称差 对称差运算△如下：A△B = (A-B)∪(B-A)
     * [1, 2, 3, 4, 7, 8, 9, 10]
     *
     * @param a
     * @param b
     * @param <T>
     * @return
     */
    public static <T> Set<T> complement(Set<T> a, Set<T> b) {
        return difference(union(a, b), intersection(a, b));
    }

    @Override
    public String toString() {
        return super.toString();
    }
}
